package com.foreveross.bsl.auth.service.impl;

import java.util.UUID;

import javax.inject.Inject;
import javax.inject.Named;

import com.foreveross.bsl.auth.AuthAccount;
import com.foreveross.bsl.auth.AuthUser;
import com.foreveross.bsl.auth.service.TicketApplication;
import com.foreveross.bsl.common.utils.exception.ApplicationException;
import com.foreveross.bsl.redis.cache.RedisCacheOperator;
/**
 * @description
 *
 * @author rening
 * @version v1.0
 *
 * @2013-7-19
 *
 */
@Named("ticketApplication")
public class TicketApplicationImpl implements TicketApplication {
	
//	public static Map<String,Object>  localCache = new HashMap<String,Object>();
	
	@Inject
	private RedisCacheOperator operator;

	public synchronized String generateTicket(Object entity) {
		UUID uuid = UUID.randomUUID();
//		String ticket = uuid.toString();
//		while (localCache.containsKey(ticket)) {
//			uuid = UUID.randomUUID();
//			ticket = uuid.toString();
//		}
//		TicketApplicationImpl.localCache.put(ticket, entity);
		String key = uuid.toString();
		if(entity instanceof AuthUser){
			key = "user" + key;
			operator.set(AuthUser.class, entity, key);
		} else {
			key = "acc" + key;
			operator.set(AuthAccount.class, entity, key);
		}
		//operator.expire(key, 30*60);
		return key;
	}

	public Object getEntity(String ticket) {
//		Object entity = TicketApplicationImpl.localCache.get(ticket);
//		if(operator.getShardedJedis().exists(ticket)){
//			operator.expire(ticket, 30*60);
//		}
		
		if(ticket.startsWith("user")){
			return operator.get(AuthUser.class, ticket);
		} else {
			return operator.get(AuthAccount.class, ticket);
		}
	}

	/* (non-Javadoc)
	 * @see com.foreveross.bsl.system.application.TicketApplication#deleteEntity(java.lang.String)
	 */
	@Override
	public void deleteEntity(String ticket) {
//		localCache.remove(ticket);
		operator.getShardedJedis().del(ticket);
	}

	/* (non-Javadoc)
	 * @see com.foreveross.bsl.system.application.TicketApplication#getAppKey(java.lang.String)
	 */
	public String getAccountId(String ticket) {
//		Object entity = TicketApplicationImpl.localCache.get(ticket);
		Object entity;
		if(ticket.startsWith("user")){
			entity = operator.get(AuthUser.class, ticket);
		} else {
			entity = operator.get(AuthAccount.class, ticket);
		}
		if(entity == null){
			throw new ApplicationException("", "用户未登录或已过期。");
		}
		if(entity instanceof AuthUser){
			return ((AuthUser)entity).getAccountId();
		} else {
			return ((AuthAccount)entity).getAccountId();
		}
	}
}
